﻿@using Sample.Models
@inject TodoContext Context

<BSForm>
    <BSFormGroup>
        <BSLabel For="staticId" class="col-sm-2">Id</BSLabel>
        <BSCol SM="10">
            <BSInput InputType="InputType.Text" IsReadonly="true" id="staticId" Value="@Todo.Id.ToString()" />
        </BSCol>
    </BSFormGroup>
    <BSFormGroup>
        <BSLabel For="inputText" class="col-sm-2">Text</BSLabel>
        <BSCol SM="10">
            <BSInput InputType="InputType.Text" id="inputText" placeholder="Enter the text of the todo"  Value="@Todo.Text" />
        </BSCol>
    </BSFormGroup>
    <div class="form-group row">
        <label class="col-sm-2 form-check-label" for="checkDone">Done</label>
        <div class="col-sm-10">
            <input type="checkbox" class="form-check-input" id="checkDone" @bind="@Todo.IsDone" />
        </div>
    </div>
    <BSCol SM="10" SMOffset="2">
        <BSButton Color="Color.Primary" @onclick="@onclick">Submit</BSButton>
    </BSCol>
</BSForm>

@functions {
    [Parameter] int SelectedId { get; set; }
    [Parameter] Action NewTodoAdded { get; set; }

    TodoItem Todo { get; set; } = new TodoItem();

    protected async override Task OnInitAsync()
    {
        if (Context.Todos == null)
        {
            await Context.Initialize();
        }
        if (SelectedId == 0)
        {
            Todo = new TodoItem();
        }
        else
        {
            SetTodo();
        }
    }

    protected async override Task OnParametersSetAsync()
    {
        if (Context.Todos == null)
        {
            await Context.Initialize();
        }
        SetTodo();
    }

    void SetTodo()
    {
        if (Context.Todos == null)
        {
            return;
        }
        var query = from todo in Context.Todos
                    where todo.Id == SelectedId
                    select todo;
        var item = query.FirstOrDefault();
        Todo = item != null ? item : new TodoItem();
    }

    async void onclick()
    {
        if (Todo.Id == 0)
        {
            Context.Todos.Add(Todo); //add new todo to the context
        }
        await Context.SaveChanges();
        StateHasChanged();
        NewTodoAdded();
    }

}